<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="referrer" content="no-referrer">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>网络收藏夹|文件</title>
    <link rel="icon" href="favicon.ico" type="image/x-icon"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
    <link rel="stylesheet" href="layui/css/layui.css">
    <style type="text/css">


			.layui-laypage-prev i, .layui-laypage-next i{
                font-size: 12px;
			}

			.home-icon {
				width: 30px;
				height: 30px;
				margin-top: 16px;
				margin-left: 20px;
				cursor: pointer;
			}

			.header {
			    position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 60px;
                background-color: #0A0E11;
			}

			.center {
			    position: fixed;
                width: 100%;
                top: 60px;
                bottom: 44px;
                overflow: auto;
			}

			.footer {
			    position: fixed;
                bottom: 0;
                width: 100%;
                text-align: center;
                height: 44px;
                line-height: 44px;
                background-color: #f5f7fa;
			}

			#logout {
                margin-top: 20px;
                margin-right: 20px;
                float: right;
			}

			.main {
			    padding: 15px;
			}

			.layui-table-link {
                cursor: pointer;
            }
            .file-info .file-icon {
                margin-right: 10px;
                width: 16px;
                height: 16px;
                border: none;
                vertical-align: sub;
            }

            .file-info .file-share {
                cursor: pointer;
                margin-right: 10px;
                margin-left: 10px;
                font-size: 14px;
                display: none;
                float: right;
            }

            .file-info:hover .file-share {
                display: block;
            }

            .layui-breadcrumb a {
                color: #303133!important;
            }

    </style>
</head>
<body>
<div class="header">
    <a href="index.html"><img class="home-icon" src="images/home.svg" alt=""></a>
    <button class="layui-btn layui-btn-xs" type="button" id="logout">退出</button>
</div>
<div class="center" id="center">
    <div class="main" id="main">
        <!-- 当前路径 -->
        <input type="hidden" id="parent" value="">
        <!-- 按钮 -->
        <div class="layui-btn-container">
            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="goBack"
                    style="padding: 0 6px;">
                <i class="layui-icon layui-icon-left"></i>
            </button>
            <button type="button" class="layui-btn layui-btn-sm" id="upload">上传文件</button>
            <button type="button" class="layui-btn layui-btn-sm" id="newFolder">新建文件夹</button>
            <button type="button" class="layui-btn layui-btn-sm" id="delAll">全部删除</button>
            <button type="button" class="layui-btn layui-btn-sm" id="move">移动到</button>
            <button type="button" class="layui-btn layui-btn-sm" id="downloadAll">备份</button>
        </div>
        <!-- 进度条 -->
        <div class="layui-progress" lay-showPercent="true" lay-filter="progress">
            <div class="layui-progress-bar" lay-percent="100%"></div>
        </div>
        <div style="margin-top: 10px;color:#303133">
            <div class="layui-inline">
                搜索文件：<input class="layui-input" id="searchName" placeholder="请输入文件名称" autocomplete="off"
                            style="display: inline-block;width: 180px;height: 30px;margin-right: 10px;font-size: 12px;">
            </div>
            <div class="layui-inline" style="height: 30px;line-height: 30px;">
                当前路径：<span class="layui-breadcrumb" lay-separator="/" lay-filter="floors" id="floors"></span>
            </div>
        </div>
        <!-- 数据表格 -->
        <table id="fileList" lay-filter="fileList"></table>
        <!-- 操作 -->
        <script type="text/html" id="operates">
            <a class="layui-btn layui-btn-xs" lay-event="download">下载</a>
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">修改</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        </script>
        <div style="color:#303133">已使用：<span id="used">0 M</span> / 剩余：<span id="rest">0 M</span></div>
    </div>
</div>
<div class="footer">
    © 2020 网络收藏夹 || 网络收藏夹版权所有
</div>
<div id="folderTree" style="display: none;padding: 10px"></div>
<script src="layui/jquery-3.1.1.min.js" type="text/javascript" charset="utf-8"></script>
<script src="layui/layui.js"></script>
<script>
    layui.use(['element', 'layer', 'table', 'upload', 'tree'], function() {
        var element = layui.element;
        var layer = layui.layer;
        var table = layui.table;
        var upload = layui.upload;
        var tree = layui.tree;

        var indexMap = new Map();// 弹出层索引容器

        // jQuery全局拦截器
        $(document).ajaxSuccess(function(event,xhr,options){
            var result = xhr.responseJSON;
            if(result != undefined && result.code == "401"){
                window.location.href= "login.html";
            }
        });

        //加载数据
        table.render({
            elem: '#fileList'
            , url: 'file/list/' //数据接口
            , headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")}
            , page: {
                layout: ['count', 'prev', 'page', 'next', 'skip']
                , prev: '上一页'
                , next: '下一页'
                , limit: 20
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.page.total,
                    "data": res.data.page.list, //解析数据列表
                    "parent": res.data.parent,
                    "floors": res.data.floors
                };
            }
            , done: function (res, curr, count) {
                $("#parent").val(res.parent);
                var html = '';
                $(res.floors).each(function(index,item){
                    html += '<a href="javascript:position('+ item.id +')">'+ item.filename +'</a>';
                });
                $("#floors").empty().append('<a href="">根目录</a>').append(html);
                element.render('breadcrumb','floors');
                // 解决无数据table样式错乱
                if(count == 0){
                    $("th[data-key='1-0-4']").css("border-right", "0");
                }
            }
            , cols: [[ //表头
                {type: 'checkbox'}
                , {
                    field: 'filename', title: '目录/文件', minWidth: 200, templet: function (d) {
                        var html = '<div class="file-info">';
                        if (d.isDir == 1) {
                            html += '<a class="layui-table-link" onclick="goto(this)" data-id="' + d.id + '" data-directory="' + (d.isDir == 1) + '"><img class="file-icon" src="images/folder.svg"/>' + d.filename + '</a>';
                        } else {
                            html += '<a class="layui-table-link" onclick="goto(this)" data-id="' + d.id + '" data-directory="' + (d.isDir == 1) + '"><img class="file-icon" src="' + suffix(d.filename) + '"/>' + d.filename + '</a>';
                            html += '<i class="file-share layui-icon layui-icon-release" onclick="share(this)" data-id="' + d.id + '" title="分享文件"></i>';
                        }
                        html += '</div>';
                        return html;
                    }
                }
                , {
                    field: 'size', title: '大小', templet: function (d) {
                        return d.isDir == 1 ? "0 B" : change(d.size);
                    }
                }
                , {
                    field: 'updateTime', title: '上传时间'
                }
                , {title: '操作', width: 170, toolbar: '#operates', fixed: 'right'}
            ]]
        });

        // 加载文件夹树
        window.loadTree = function(){
            $.ajax({
                type: "GET",
                url: "file/tree",
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    if (result.code == 0) {
                        // 渲染文件夹树结构
                        tree.render({
                            elem: '#folderTree'
                            , data: result.data
                            , showLine: false
                            , onlyIconControl: true
                            , click: function (obj) {
                                layer.confirm('确认移动到此文件夹吗?', function (index) {
                                    var checkStatus = table.checkStatus('fileList');
                                    var ids = [];
                                    $.each(checkStatus.data, function (index, item) {
                                        ids.push(item.id);
                                    });
                                    $.ajax({
                                        type: "POST",
                                        url: "file/move",
                                        data: {"ids": ids.join(","), "pid": obj.data.id},
                                        dataType: "json",
                                        headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                                        success: function (result) {
                                            if (result.code == 0) {
                                                layer.msg('操作成功', {icon: 6});
                                                table.reload('fileList');
                                            } else {
                                                layer.msg('操作失败', {icon: 5});
                                            }
                                        }
                                    });
                                    layer.closeAll();
                                });
                            }
                        });
                    }
                }
            });
        };

        $(document).on("keydown", function(event){
            if(event.ctrlKey && event.key === "f"){
                $("#searchName").focus();
                // 阻止默认浏览器动作(W3C)
                var e = event;
                if ( e && e.preventDefault )
                    e.preventDefault();
                // IE中阻止函数器默认动作的方式
                else
                    window.event.returnValue = false;
                return false;
            }
        });

        window.loadCapacity = function(){
            $.ajax({
                type: "GET",
                url: "file/capacity",
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    if (result.code == 0) {
                        var data = result.data;
                        $("#used").text(change(data.usedSize));
                        $("#rest").text(change(data.capacity - data.usedSize));
                        uploadInst.reload({size: (data.capacity - data.usedSize) / 1024});
                    }
                }
            });
        };

        $("#downloadAll").click(function(){
            layer.confirm('确认备份所有文件吗？', function(index){
                layer.load(1);
                $.ajax({
                    type: "GET",
                    url: "file/count",
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        if (result.code == 0 && result.data.count > 0) {
                            downloadFile('备份.zip', 'file/downloadAll');
                        } else {
                            layer.closeAll('loading');
                            layer.msg('暂无可备份文件', {icon: 5});
                        }
                    }
                });

                layer.close(index);
            });
        });

        // 页面加载后执行
        $(function () {
            loadCapacity();
            loadTree();
        });

        // 移动
        $("#move").click(function () {
            var checkStatus = table.checkStatus('fileList');
            if (checkStatus.data.length === 0) {
                layer.msg('请选择文件');
                return false;
            }
            layer.open({
                type: 1,
                title: "移动文件(夹)",
                area: ['400px', '300px'],
                content: $('#folderTree')
            });
        });
        // 全部删除
        $("#delAll").click(function () {
            var checkStatus = table.checkStatus('fileList');
            if (checkStatus.data.length === 0) {
                layer.msg('请选择文件');
                return false;
            }
            layer.confirm('确认删除全部文件吗?', function (index) {
                var ids = [];
                $.each(checkStatus.data, function (index, item) {
                    ids.push(item.id);
                });
                $.ajax({
                    type: "POST",
                    url: "file/deleteMore",
                    data: {"ids": ids.join(",")},
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        if (result.code == 0) {
                            layer.msg('删除成功', {icon: 6});
                            table.reload('fileList');
                            loadCapacity();
                        } else {
                            layer.msg('删除失败', {icon: 5});
                        }
                    }
                });
                layer.close(index);
            });
        });

        // 搜索
        $('#searchName').bind('keypress', function (event) {
            if (event.key === "Enter") {
                table.reload('fileList', {page: {curr: 1}, where: {"name": $(this).val(), "pid": null}});
            }
        });

        // 返回
        $("#goBack").click(function () {
            $.ajax({
                type: "GET",
                url: "file/back",
                data: {"pid": $("#parent").val()},
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    if (result.code == 0) {
                        var pid = result.data ? result.data : null;
                        table.reload('fileList', {page: {curr: 1}, where: {"pid": pid, "name": ""}});
                    }
                }
            });

        });
        // 新建文件夹
        $("#newFolder").click(function () {
            layer.prompt({
                title: '新建文件夹',
                placeholder:"输入文件夹名称",
                maxlength: 100
            }, function (value, index, elem) {
                $.ajax({
                    type: "POST",
                    url: "file/folder",
                    data: {
                        "pid": $("#parent").val(),
                        "filename": value
                    },
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        if (result.code == 0) {
                            table.reload('fileList');
                            loadTree();
                        } else {
                            layer.msg(result.msg, {icon: 5});
                        }
                    }
                });
                layer.close(index);
            });
        });


        //监听工具条
        table.on('tool(fileList)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            if (layEvent === 'edit') { //修改
                layer.prompt({
                    title: '重命名文件(夹)',
                    value: data.filename,
                    maxlength: 100,
                }, function (value, index, elem) {
                    $.ajax({
                        type: "POST",
                        url: "file/rename",
                        data: {"id": data.id, "filename": value},
                        dataType: "json",
                        headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                        success: function (result) {
                            if (result.code == 0) {
                                layer.msg('修改成功', {icon: 6});
                                //同步更新缓存对应的值
                                obj.update({filename: value});
                            } else {
                                layer.msg('修改失败', {icon: 5});
                            }
                        }
                    });
                    layer.close(index);
                });
            } else if (layEvent === 'del') { //删除
                layer.confirm('确认删除文件吗？', function (index) {
                    $.ajax({
                        type: "POST",
                        url: "file/delete",
                        data: {"id": data.id},
                        dataType: "json",
                        headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                        success: function (result) {
                            if (result.code == 0) {
                                obj.del(); //移除当前行
                                layer.msg('删除成功', {icon: 6});
                                loadCapacity();
                            } else {
                                layer.msg('删除失败', {icon: 5});
                            }
                        }
                    });
                    layer.close(index);
                });
            } else if (layEvent === 'download') { //下载
                if (data.isDir == 1) {
                    layer.msg('暂不支持文件夹下载', {icon: 5});
                } else {
                    layer.confirm('确认下载文件吗？', function(index){
                        layer.close(index);

                        layer.load(1);
                        $.ajax({
                            type: "GET",
                            url: "file/exists/" + data.id,
                            dataType: "json",
                            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                            success: function (result) {
                                if (result.code == 0) {
                                    downloadFile(data.filename, "file/download/" + data.id);
                                } else {
                                    layer.closeAll('loading');
                                    layer.msg('文件已损坏', {icon: 5});
                                }
                            }
                        });
                    });
                }
            }
        });

        //上传文件
        var successful = 0;
        var aborted = 0;
        var uploadInst = upload.render({
            elem: '#upload' //绑定元素
            , url: 'file/upload/' //上传接口
            , headers: {"Authorization": "Bearer "+ localStorage.getItem("login_user_token")}
            , data: {
                "pid": function () {
                    return $("#parent").val();
                }
            }
            , multiple: true
            , accept: 'file'
            , before: function(obj){
                 layer.load(1);
            }
            , done: function(res, index, upload){
                if(res.code == 0){
                    successful++;
                }else{
                    aborted++;
                }
            }
            , allDone: function(obj){
                layer.closeAll('loading');
                if(successful == 0){
                    layer.msg('上传失败', {icon: 5});
                }else{
                    layer.msg('上传成功:' + successful+', 上传失败:' + aborted, {icon: 6});
                }
                table.reload('fileList');
                loadCapacity();
                successful = 0;
                aborted = 0;
            }
            , progress: function (n, elem) {
                element.progress('progress', n + '%');
            }
        });

        window.downloadFile = function(filename, url){
            // 此处不加载动画，只关闭动画，加载动画交给前面的函数执行
            $.ajax({
                url: url,
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                xhrFields: { responseType: "arraybuffer" },
                success: function(result){
                    layer.closeAll('loading');
                    var a = document.createElement('a');
                    a.download = filename;
                    a.style.display = 'none';
                    var blob = new Blob([result]);
                    a.href = URL.createObjectURL(blob);
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                },
                error: function(){
                    layer.closeAll('loading');
                    layer.msg('下载失败', {icon: 5});
                }
            });
        };

        window.copyText = function(value){
            var input = document.createElement('input');
            input.setAttribute('readonly', 'readonly');
            input.setAttribute('value', value);
            document.body.appendChild(input);
            input.select();
            if (document.execCommand('copy')) {
                document.execCommand('copy');
            }
            document.body.removeChild(input);
        };

        // 分享
        window.share = function (obj) {
            var id = $(obj).attr("data-id");
            layer.load(1);
            $.ajax({
                type: "GET",
                url: "file/share/" + id,
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        var url = window.location.href;
                        var path = url.substring(0,url.lastIndexOf("/"));
                        var text = path + "/file/share/download/" + result.data;
                        layer.open({
                          title: '复制以下链接分享'
                          ,content: text
                          ,btn: ['复制', '取消分享']
                          ,yes: function(index, layero){
                            copyText(text);
                            layer.msg("复制成功");
                            layer.close(index);
                          }
                          ,btn2: function(index, layero){
                            $.ajax({
                                type: "GET",
                                url: "file/share/cancel/" + id,
                                dataType: "json",
                                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                                success: function (result) {
                                    if (result.code == 0) {
                                        layer.msg("操作成功");
                                    }
                                }
                            });
                            layer.close(index);
                          }
                        });
                    } else {
                        layer.msg('文件已损坏', {icon: 5});
                    }
                }
            });
        };

        window.position = function (id) {
            table.reload('fileList', {page: {curr: 1}, where: {"pid": id}});
        }

        // 跳转
        window.goto = function (obj) {
            var that = $(obj);
            if (that.attr("data-directory") === "true") {
                table.reload('fileList', {page: {curr: 1}, where: {"pid": that.attr("data-id")}});
            } else {
                var id = that.attr("data-id");
                $.ajax({
                    type: "GET",
                    url: "file/view",
                    data: {"id": id},
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        if (result.code == 0) {
                            layer.open({
                                area:['800px','600px'],
                                type: 1,
                                title: '文件内容',
                                content: '<xmp style="padding: 10px;margin: 0">' + result.data + '</xmp>'
                            });
                        } else {
                            layer.msg('暂不支持文件查看', {icon: 5});
                        }
                    }
                });
            }
        };

        /**
         * 格式化文件大小
         */
        window.change = function (limit) {
            var size = "";
            if (limit < 0.1 * 1024) {//小于0.1KB，则转化成B
                size = limit.toFixed(2) + " B"
            } else if (limit < 0.1 * 1024 * 1024) {//小于0.1MB，则转化成KB
                size = (limit / 1024).toFixed(2) + " KB"
            } else if (limit < 0.1 * 1024 * 1024 * 1024) {//小于0.1GB，则转化成MB
                size = (limit / (1024 * 1024)).toFixed(2) + " MB"
            } else {//其他转化成GB
                size = (limit / (1024 * 1024 * 1024)).toFixed(2) + " GB"
            }
            size = size.replace(".00", "");
            return size;
        };

        /**
         * 格式化时间
         * @param time
         * @returns {string}
         */
        window.format = function (time) {
            // 补0   例如 2018/7/10 14:7:2  补完后为 2018/07/10 14:07:02
            function addZero(num) {
                if (num < 10)
                    return "0" + num;
                return num;
            }

            var date = new Date(time);
            // 按自定义拼接格式返回
            return date.getFullYear() + "/" + addZero(date.getMonth() + 1) + "/" + addZero(date.getDate()) + " " +
                addZero(date.getHours()) + ":" + addZero(date.getMinutes()) + ":" + addZero(date.getSeconds());
        };
        // 判断后缀
        window.suffix = function (url) {
            var suffix = url.substring(url.lastIndexOf("."));
            if (suffix === ".bat")
                return "images/bat.svg";
            else if (suffix === ".xls" || suffix === ".xlsx")
                return "images/excel.svg";
            else if (suffix === ".exe")
                return "images/exe.svg";
            else if (suffix === ".md")
                return "images/markdown.svg";
            else if (suffix === ".mp3" || suffix === ".wma")
                return "images/music.svg";
            else if (suffix === ".pdf")
                return "images/pdf.svg";
            else if (suffix === ".png" || suffix === ".jpg" || suffix === ".ico")
                return "images/photo.svg";
            else if (suffix === ".gif")
                return "images/gif.svg";
            else if (suffix === ".svg")
                return "images/svg.svg";
            else if (suffix === ".ppt" || suffix === ".pptx")
                return "images/ppt.svg";
            else if (suffix === ".sh")
                return "images/shell.svg";
            else if (suffix === ".gz" || suffix === ".tar" || suffix ===".tgz" || suffix === ".xz")
                return "images/tar.svg";
            else if (suffix === ".txt")
                return "images/txt.svg";
            else if (suffix === ".properties")
                return "images/properties.svg";
            else if (suffix === ".yml")
                return "images/yml.svg";
            else if (suffix === ".mp4" || suffix === ".avi" || suffix === ".flv" || suffix === ".rmvb")
                return "images/video.svg";
            else if (suffix === ".doc" || suffix === ".docx")
                return "images/word.svg";
            else if (suffix === ".xml")
                return "images/xml.svg";
            else if (suffix === ".zip" || suffix === ".rar" || suffix === ".war" || suffix === ".7z")
                return "images/zip.svg";
            else if (suffix === ".sql")
                return "images/sql.svg";
            else if (suffix === ".db")
                return "images/database.svg";
            else if (suffix === ".java")
                return "images/java.svg";
            else if (suffix === ".py")
                return "images/python.svg";
            else if (suffix === ".php")
                return "images/php.svg";
            else if (suffix === ".json")
                return "images/json.svg";
            else if (suffix === ".css")
                return "images/css.svg";
            else if (suffix === ".js")
                return "images/js.svg";
            else if (suffix === ".html")
                return "images/html.svg";
            else if (suffix === ".jar")
                return "images/jar.svg";
            else if (suffix === ".apk")
                return "images/apk.svg";
            else if (suffix === ".desktop")
                return "images/desktop.svg";
            else if (suffix === ".lnk" || suffix === ".url")
                return "images/link.svg";
            else if (suffix === ".rpm")
                return "images/rpm.svg";
            else if (suffix === ".iso")
                return "images/iso.svg";
            else if (suffix === ".dll")
                return "images/dll.svg";
            else if (suffix === ".bak")
                return "images/bak.svg";
            else
                return "images/unknown.svg";
        }
        // 格式化时间
        window.dateFormat = function(fmt, date) {
            var ret;
            const opt = {
                "y+": date.getFullYear().toString(),        // 年
                "M+": (date.getMonth() + 1).toString(),     // 月
                "d+": date.getDate().toString(),            // 日
                "H+": date.getHours().toString(),           // 时
                "m+": date.getMinutes().toString(),         // 分
                "s+": date.getSeconds().toString()          // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
            };
            for (var k in opt) {
                ret = new RegExp("(" + k + ")").exec(fmt);
                if (ret) {
                    fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
                };
            };
            return fmt;
        };

        // 登出
        $("#logout").click(function () {
            layer.confirm('确认退出系统吗？', function(index){
                layer.close(index);

                localStorage.clear();
                window.location.href = "login.html";
            });
        });
    });
</script>
</body>
</html>
